import axios from "axios";
const API_PROXY_PREFIX='/api'
const ServerURL = process.env.NODE_ENV === 'production' ? 'http://124.71.234.61:21021' : API_PROXY_PREFIX
const UploadUtil = {
  actionURL: ServerURL + "/Home/UploadFilesAsync",
  mockURL: ServerURL + "/Home/Upload",
  imgServ: ServerURL + "/Home/GetImageAsync?sysRowId=",
  accessToken: "Bearer " + localStorage.getItem("access-token"),
  uploadPic: async function(files, objectId, objectName, objectField) {
    let formData = new FormData();
    files.forEach((element) => {
      formData.append("files", element.originFileObj);
    });
    formData.append("objectId", objectId);
    formData.append("objectName", objectName);
    formData.append("objectField", objectField);

    var resp = {};
    await axios({
      method: "POST",
      url: this.actionURL,
      data: { formData },
      headers: {
        Authorization: this.accessToken,
      },
    })
      .then((response) => response.json())
      .then((responseData) => {
        resp = responseData;
      })
      .catch((err) => {
        message.error("图片上传失败");
      });
    if (resp && resp.success) {
      return resp.result;
    } else {
      return "";
    }
  },
  getBase64: function(img, callback) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  },
  beforeUpload: function(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("仅限于 JPG/PNG 文件!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("文件大小不得大于 2MB!");
    }
    return isJpgOrPng && isLt2M;
  },
};

export { UploadUtil };
